#include <stdio.h>
#include <string.h>
#include "xfat.h"
#include "xdisk.h"

extern xdisk_driver_t vdisk_driver;

const char *disk_path = "../FAT32_Sourse/tools/DiskImage/disk.img";
const char *disk_path_test = "../FAT32_Sourse/tools/DiskImage/disk_test.img";
static uint32_t write_buffer[160 * 1024];
static uint32_t read_buffer[160 * 1024];

xdisk_t disk;

int disk_io_test(void)
{
    int err;
    xdisk_t disk_test;
    disk_test.driver = &vdisk_driver;
    memset(read_buffer, 0, sizeof(read_buffer));

    for (int i = 0; i < sizeof(write_buffer) / sizeof(uint32_t); i++)
    {
        write_buffer[i] = i;
    }

    err = xdisk_open(&disk_test, "vdisk_test", &vdisk_driver, (void *)disk_path_test);
    if (err)
    {
        printf("open vdisk failed\n");
        return -1;
    }

    err = xdisk_write_sector(&disk_test, (uint8_t *)write_buffer, 0, 2);
    if (err)
    {
        printf("write vdisk failed\n");
        return -1;
    }

    err = xdisk_read_sector(&disk_test, (uint8_t *)read_buffer, 0, 2);
    if (err)
    {
        printf("read vdisk failed\n");
        return -1;
    }

    err = memcmp((uint8_t *)read_buffer, (uint8_t *)write_buffer, disk_test.sector_size * 2);
    if (err != 0)
    {
        printf("read data not equal\n");
        return -1;
    }

    err = xdisk_close(&disk_test);
    if (err)
    {
        printf("close vdisk failed\n");
        return -1;
    }

    printf("disk io test succeed!\n");
    return 0;
}

int disk_part_test(void)
{
    uint32_t count;
    xfat_err_t err;

    printf("Partition Test Start...\n");
    err = xdisk_get_part_count(&disk, &count);
    if(err < 0)
    {
        printf("Partition count Test failed!\n");
        return err;
    }

    for(int i = 0; i < count; i++)
    {
        xdisk_part_t part;
        int err = xdisk_get_part_msg(&disk, &part, i);
        if(err < 0)
        {
            printf("get partition msg failed!\n");
            return -1;
        }
        printf("sector_num: %d, start_sector: %d, count: %d, capacity: %.0f M\n", i, part.start_sector, part.total_sector, 
                part.total_sector * disk.sector_size / 1024 / 1024.0);
    }



    printf("main partition count:%d\n", count);
    return 0;
}


int main(void)
{
    int err;

    printf("Test Start!\n");

    // err = disk_io_test();
    // if (err)
    // {
    //     return err;
    // }

    err = xdisk_open(&disk, "vdisk", &vdisk_driver, (void *)disk_path);
    if (err)
    {
        printf("open vdisk failed\n");
        return -1;
    }

    err = disk_part_test();
    if (err)
    {
        return err;
    }

    err = xdisk_close(&disk);
    if (err)
    {
        printf("close vdisk failed\n");
        return -1;
    }

    printf("Test End!\n");
    return 0;
}